package org.openintents.oiserverdemo;

import java.util.Map;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;

public class OIServerPreferenceActivity extends PreferenceActivity
	implements SharedPreferences.OnSharedPreferenceChangeListener{

	/* 
	 * Constants
	 */
	private final int DIALOG_DUPLICATE_PREF = 1;
	
	SharedPreferences prefs;
	
	/* (non-Javadoc)
	 * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		Log.d(getPackageName(), "*** CHANGED "+key+" ****");
		boolean enableSSL = sharedPreferences.getBoolean("prefSSLEnable", false);
		int sslPort = Integer.parseInt(sharedPreferences.getString("prefSSLServerPort", "8888"));
		int serverPort = Integer.parseInt(sharedPreferences.getString("prefServerPort", "8080"));
		
		if(sslPort == serverPort && enableSSL) {
			SharedPreferences.Editor editor = sharedPreferences.edit();
			showDialog(DIALOG_DUPLICATE_PREF);
			editor.putString("prefSSLServerPort", "8888");
			editor.putString("prefServerPort", "8080");
			editor.commit();
			onContentChanged();
		}
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(OIServerPreferenceActivity.this);
		switch(id)
		{
		case DIALOG_DUPLICATE_PREF:
			builder.setMessage("The 'Server Port' and 'SSL Server Port' cannot be the same" +
					"\nThe default values have been restored" +
					"\nSSL Server Port: 8888\n" +
					"Server Port: 8080");
			builder.setTitle("OIServerDemo - Preferences");
			builder.setPositiveButton("OK", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int arg1) {
					dialog.dismiss();
				}
			});
			
		break;
		default:
			return super.onCreateDialog(id);
		}
		return builder.create();
	}
}
